import { Modal, Progress, Toast } from 'antd-mobile'
import React, { useEffect, useState } from 'react'
import { PingTuanStyle } from './style'
import { PopupStyle } from '../home/minGoodsDetail/style'
import { useHistory } from 'react-router-dom'
import { createPurchaseOrder, updateOrderAddress } from '@api/home'
import { useDispatch, useSelector } from 'react-redux'
import { selectedAddressAction } from '@store/actionCreators'

import 'swiper/swiper.less'
import { Swiper, SwiperSlide } from 'swiper/react'
import SwiperCore, { Autoplay } from 'swiper'
SwiperCore.use([Autoplay])

const PingTuanTimer = (props) => {
  let Timer = null
  const { endtime } = props
  const [timerObject, settimerObject] = useState({})

  useEffect(() => {
    timer(endtime)
    return () => {
      clearInterval(Timer)
    }

  }, [timerObject, Timer, endtime])



  return (
    <div className="bottom flex-row">
      拼单时间剩余: <p className="flex-row"> <span> {timerObject.day} </span> 天 <span>{timerObject.hour}</span> 时 <span> {timerObject.min} </span> 分 <span> {timerObject.sec} </span> 秒 </p>
    </div>
  )

  function timer(expiredTime) {
    Timer = setInterval(() => {
      let timerObj = {}
      let now = expiredTime - Date.parse(new Date()) / 1000

      timerObj.day = Math.floor(now / 3600 / 24);
      timerObj.hour = Math.floor((now - timerObj.day * 3600 * 24) / 3600);
      timerObj.min = Math.floor((now - timerObj.day * 3600 * 24 - timerObj.hour * 3600) / 60);
      timerObj.sec = now - timerObj.day * 3600 * 24 - timerObj.hour * 3600 - timerObj.min * 60;
      settimerObject(timerObj)
    }, 1000)
  }
}

const PingTuanProgress = (props) => {

  const { neednum, lacknum } = props

  const progress = ((neednum - lacknum) / neednum).toFixed(2)

  console.log(progress)

  return (
    <div className="center flex-row">
      {/* 进度条 */}
      <div className="tiao ">
        <Progress percent={progress * 100} position="normal" unfilled={true}
          style={{
            width: '7.13rem',
            backgroundColor: '#FFE4D5',
            borderRadius: '.5rem',
          }}
          barStyle={{
            borderRadius: '.5rem',
          }}
        />

      </div>
      <span> {`${progress * 100}%`} </span>
      <div className="tip">
        <img src="https://res.lexiangpingou.cn/images/826/2020/09/mTd4t9IhtdL74iIt6tu64CWt3dLthD.png" alt="" />
      </div>
    </div>
  )
}

const JoinTuan = (props) => {

  const history = useHistory();

  const dispatch = useDispatch()

  const [joinModal, setjoinModal] = useState(false)
  const [goodsNum, setgoodsNum] = useState(1)

  const appConfig = useSelector(state => state.appConfig)
  const defaultAddress = useSelector(state => state.defaultAddress)
  const { uniacid, isApplet } = appConfig
  const { goodsid, lacknum, pack_type, tuan_id, car_size, car_type, specs } = props

  const tuan = <button className="join-tuan" onClick={e => { setjoinModal(!joinModal) }}>参与拼单</button>
  const seetuan = <button className="join-tuan" onClick={e => { isApplet ? window.navigateToWebWiew(`/group/${tuan_id}`) : history.push(`/group/${tuan_id}`) }}>我的团</button>

  useEffect(() => {

  }, [joinModal, goodsNum])

  return (
    <>
      {  props.uniacid === uniacid ? seetuan : tuan}
      <Modal
        visible={joinModal}
        onClose={e => { setjoinModal(!joinModal) }}
        maskClosable={true}
        transparent
        popup={true}
        animationType='slide-up'
        title="参与拼单"
        style={{
          backgroundColor: 'white',
          borderRadius: '.25rem .25rem 0 0'
        }}
      >
        <PopupStyle >
          <div className="goods-option-popup" >
            <div className="bottom" >
              <div className="num flex-row">
                <div className="num-limit">需求数量 {/*<span>{minDetail.min_num}起发</span>*/}  </div>
                <div className="num-input">
                  <div className="content flex-row">
                    <div className="cube" onClick={e => { changeGoodsNum('reduce') }} > - </div>
                    <input className="goodsnum" type="number" name="goodsNum" value={goodsNum} onChange={e => { handelInput(e) }} />
                    <div className="cube" onClick={e => { changeGoodsNum('plus') }} > + </div>
                  </div>
                </div>
              </div>
              <button className="caigou" onClick={e => { pingtuan() }}>
                参与拼单
              </button>
            </div>
          </div>
        </PopupStyle>
      </Modal>
    </>
  )

  function pingtuan() {

    let addressConfig = {
      deposit_orderno: '',
      province: defaultAddress.proc,
      city: defaultAddress.cityc,
      county: defaultAddress.countyc,
      detailed_address: defaultAddress.detailed_address
    }

    let config = {
      tuan_id: tuan_id,
      id: goodsid,
      cartType: car_type,
      cartSize: car_size,
      packType: pack_type,
      uniacid: uniacid,
      min_num: goodsNum, // 购买数量
      buy: '1', // 传 1 表示购买 ,
      specs,
    }

    createPurchaseOrder(config).then(res => {
      if (res.status === 200) {
        addressConfig.deposit_orderno = res.data
        updateOrderAddress(addressConfig).then(rex => {
          // this.props.popupOnOff()
          dispatch(selectedAddressAction({})) // 清除 选择地址
          isApplet ? window.navigateToWebWiew(`/submit/${res.data}/${tuan_id}`) : history.push(`/submit/${res.data}/${tuan_id}`)
        })

      } else if (res.status === 400) {
        Toast.info(res.msg)
      }

    })


  }

  function changeGoodsNum(type) {
    // 改变购买商品数量
    if (type === 'reduce') {
      if (goodsNum <= 0) {
        Toast.info('不能再减啦', 1)
      } else {
        setgoodsNum(goodsNum - 1)
      }
    } else {

      if (goodsNum >= lacknum) {
        Toast.info('超出承载量', 1)
      } else {
        setgoodsNum(parseInt(goodsNum) + 1)
      }
    }
  }
  function handelInput(e) {
    // 保存输入的商品数量
    if (parseInt(e.target.value) > lacknum) {
      Toast.info('超出承载量', 1)
    } else {
      setgoodsNum(e.target.value)
    }
  }
}


const TuanItem = (props) => {


  const { province, name, index, city, neednum, lacknum, endtime } = props

  return (
    <>
      <div style={index !== 0 ? {
        backgroundColor: 'rgba(34,40,54,.2)',
        height: '1px',
        border: 'none',
        width: '100%'
      } : {}}> </div>
      <div className="container-pt"
        style={{ padding: '0 .32rem', paddingTop: '.4rem', paddingBottom: '.4rem' }}
      >
        <div className="c-top flex-row">
          <div className="left flex-row">
            <img className="avatar" src="https://res.lexiangpingou.cn/images/826/2020/10/Jrw73uRJjszsJJ3ujjZJVAjWvBVrbF.png" alt="" />
            <div className="info">
              <p className="tname">
                {name}
              </p>
              <p className="tcity">
                {`${province}${city}`}
              </p>
            </div>
          </div>
          <div className="right flex-row">
            <div className="tschedule">
              <p className="yiping">
                已拼{neednum - lacknum}
              </p>
              <p className="haicha" >
                还差<span> {lacknum} </span>
              </p>
            </div>

            <JoinTuan  {...props} />

          </div>
        </div>

        <PingTuanProgress lacknum={parseInt(lacknum)} neednum={parseInt(neednum)} />

        <PingTuanTimer endtime={endtime} />
      </div>
    </>
  )



}


const PingTuan = (props) => {

  const history = useHistory()
  const { groupList, gid } = props

  return (
    <>
      <PingTuanStyle>
        <div className="pingtuan-box">
          <div className="pt-top flex-row">
            <p>这些人已发起拼单，可立即参与拼单</p>
            <span onClick={e => { history.push('/pingtuanlist/' + gid) }} >查看全部</span>
          </div>

          <div className="pingtuan-content">

            <Swiper tag="section" wrapperTag="ul"
              slidesPerView={'2'}
              autoplay={{
                delay: 6000,
                disableOnInteraction: false,
                // waitForTransition: true
                reverseDirection: true // 反向轮播

              }}
              direction="vertical"
              noSwiping={true}
              noSwipingClass="stop-swiping"
              loop={false} // 耗能
            >
              {
                groupList &&
                groupList.map((item, key) => (
                  <SwiperSlide
                    key={key + item.tuan_id}
                    tag="li"
                  >
                    <TuanItem index={key}  {...item} />
                  </SwiperSlide>

                ))
              }

            </Swiper>


          </div>

        </div>
      </PingTuanStyle>
    </>
  )
}

export default PingTuan